import { normalApp } from './apps/index.js'
import * as System from './apps/system/index.js'
import { initResizable } from './resizable.js'
import { getStorage } from './bridge.js'
import EventBus from './eventbus.js'

window.$eventbus = new EventBus()

const apps = {
  ...normalApp,
  System,
}

const updateApp = (appKey, enabled) => {
  const app = apps[appKey]
  const root = document.querySelector(`#${appKey}`)
  const container = root.querySelector('[data-slot]') || root

  let onMountHook
  if (enabled) {
    root.classList.remove('hide')
    app.render({
      onMount: (func) => {
        onMountHook = func
      },
      root: container,
    })
    onMountHook && onMountHook()
  } else {
    root.classList.add('hide')
    app.unmount({
      root: container,
    })
  }
}

window.$eventbus.on('appUpdate', ({ data }) => {
  const { key, enabled } = data
  updateApp(key, enabled)
})

let keyCache = {}
window.addEventListener('blur', (e) => {
  keyCache = {}
}, true)
document.addEventListener('keydown', (e) => {
  keyCache[e.key] = 1
  const keyStr = Object.keys(keyCache).sort().join('_')
  window.$eventbus.emit('appKeydown', keyStr)
})

document.addEventListener('keyup', (e) => {
  delete keyCache[e.key] 
})

const appRoot = document.querySelector('#app')
document.addEventListener('DOMContentLoaded', async () => {
  const [appConfigMap] = await Promise.all([
    getStorage('appConfigMap'),
    initResizable(),
  ])
  if (appConfigMap) {
    appConfigMap.System = true
  }
  console.log('init:', appConfigMap)

  Object.keys(apps).forEach((appKey) => {
    const enabled = !appConfigMap || appConfigMap[appKey]
    updateApp(appKey, enabled)
  })

  appRoot.classList.remove('app-cloak')
})
